package com.example.myapplication;

import com.example.baselib.utils.PermissionUtils;
import com.example.baselib.utils.SPUtils;
import com.example.baselib.utils.UIUtils;
import com.example.baselib.utils.log.LogUtils;
import com.google.gson.Gson;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.ArrayList;
import java.util.List;

public class SplashAbility extends Ability {

    Text ttTimer;
    Button button;
    PageSlider pageSlider;
    RadioContainer container;

    List<Component> pageViews;
    boolean isFirst = true;
    int count = 5;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_splash);
        pageSlider = UIUtils.findComponentFromId(this, ResourceTable.Id_page_slider);
        container = UIUtils.findComponentFromId(this, ResourceTable.Id_radio_container);

        pageViews = new ArrayList<>();

        initDefComponent();

        initPermission();
    }

    //设置默认的
    private void initDefComponent() {
        //获取布局文件
        Component component1 = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_slice_splash_1, null, false);
        ttTimer = UIUtils.findComponentFromId(component1, ResourceTable.Id_tt_timer);
        //适配数据绑定
        pageViews.add(component1);
        initProvider();

        ttTimer.setVisibility(Component.HIDE);
        container.setVisibility(Component.HIDE);
        pageSlider.setClickable(false);
        pageSlider.setTouchFocusable(false);
    }

    //首次授权成功后
    private void initComponent() {
        if (isFirst()) {
            ttTimer.setVisibility(Component.HIDE);
            container.setVisibility(Component.VISIBLE);
            pageSlider.setClickable(true);
            pageSlider.setTouchFocusable(true);

            Component component2 = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_slice_splash_2, null, false);
            button = UIUtils.findComponentFromId(component2, ResourceTable.Id_btn);
            pageViews.add(component2);

            pageSlider.getProvider().notifyDataChanged();
        } else {
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setRgbColor(new RgbColor(80, 80, 80));
            shapeElement.setShape(ShapeElement.OVAL);
            ttTimer.setBackground(shapeElement);

            ttTimer.setVisibility(Component.VISIBLE);
            container.setVisibility(Component.HIDE);
            pageSlider.setClickable(false);
            pageSlider.setTouchFocusable(false);
            EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
            handler.postTimingTask(new Runnable() {
                @Override
                public void run() {
                    if (count <= 1) {
                        handler.removeTask(this);

                        // Ability 跳转
                        Intent mIntent = new Intent();
                        mIntent.setAction(MainAbility.ACTION);
                        startAbility(mIntent);
                        terminateAbility();
                        return;
                    }
                    ttTimer.setText(count + "");
                    handler.postTimingTask(this, 1000);
                    count -= 1;
                }
            }, 100);
        }

        initListener();

        container.mark(0);
        pageSlider.setCurrentPage(0);
        setRadioStyle(0);
    }


    //适配绑定
    private void initProvider() {
        pageSlider.setProvider(new PageSliderProvider() {
            @Override
            public int getCount() {
                return pageViews == null ? 0 : pageViews.size();
            }

            @Override
            public Object createPageInContainer(ComponentContainer componentContainer, int i) {
                Component component = pageViews.get(i);
                componentContainer.addComponent(component);
                return component;
            }

            @Override
            public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
                componentContainer.removeComponent((Component) o);
            }

            @Override
            public boolean isPageMatchToObject(Component component, Object o) {
                return component == o;
            }
        });
    }

    private void initListener() {
        //布局文件改变监听器
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i) {
                LogUtils.i("onPageSlideStateChanged(%d)", i);
            }

            @Override
            public void onPageChosen(int i) {
                LogUtils.i("onPageChosen(%d)", i);
                container.mark(i);
                setRadioStyle(i);
            }
        });

        //指示组件 监听器
        container.setMarkChangedListener((radioContainer, i) -> {
            LogUtils.i("onCheckedChanged(radio, %d),isSelected = %s", i, radioContainer.isSelected());
            pageSlider.setCurrentPage(i);
            setRadioStyle(i);
        });

        //页面跳转
        button.setClickedListener(component -> {
            String name = "demo.json";
            SPUtils.openSPFile(name);
            SPUtils.put("isFirst", "false");

            Operation operation = new Intent.OperationBuilder()
                    .withAction(MainAbility.ACTION)
                    .build();

            // Ability 跳转
            Intent mIntent = new Intent();
            mIntent.setOperation(operation);
            startAbility(mIntent);
            terminateAbility();
        });
    }

    //设置指示器样式
    private void setRadioStyle(int index) {
        if (container == null || container.getChildCount() == 0) {
            LogUtils.w("没有相关指示器组件");
            return;
        }
        if (index < 0 || index > container.getChildCount() - 1) {
            index = 0;
        }
        LogUtils.i("index = %d,childCount = %d", index, container.getChildCount());
        RadioButton radioButton;
        ShapeElement shapeElement;
        RgbColor rgbColor;
        for (int i = 0; i < container.getChildCount(); i++) {
            radioButton = (RadioButton) container.getComponentAt(i);
            shapeElement = new ShapeElement();
            //绘制圆形
            shapeElement.setShape(ShapeElement.OVAL);
            //默认颜色
            rgbColor = new RgbColor(240, 128, 128);
            if (i == index) {
                //选中的颜色
                rgbColor = new RgbColor(255, 57, 57);
                radioButton.setSelected(true);
            } else {
                radioButton.setSelected(false);
            }
            shapeElement.setRgbColor(rgbColor);
            radioButton.setButtonElement(shapeElement);
        }

    }

    //是否为首次加载
    private boolean isFirst() {
        String has = PermissionUtils.verifyPermission(this, "ohos.permission.READ_MEDIA");
        if (has == null) {
            String name = "demo.json";
            SPUtils.openSPFile(name);
            String isF = SPUtils.get("isFirst", "true");
            if ("false".equals(isF)) {
                isFirst = false;
            }
        }
        return isFirst;
    }


    //获取用户权限
    private void initPermission() {
        String[] ps = {
                "ohos.permission.READ_MEDIA",
                "ohos.permission.WRITE_MEDIA"
        };
        if (!PermissionUtils.hasPermission(this, ps)) {
            //是否有被拒绝的权限
            String[] prohibitP = PermissionUtils.prohibitPermission(this, ps);
            if (prohibitP != null) {
                // todo 被拒绝的权限 提示手动开启
                initComponent();
                LogUtils.i("当前已经拒绝的权限 %s ", new Gson().toJson(prohibitP));
            } else {
                requestPermissionsFromUser(ps, 1011);
            }
        } else {
            // 权限已被授予
            initComponent();
        }

    }


    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1011:
                if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    LogUtils.i("储存权限授权成功 ");
                    initComponent();
                } else {
                    // todo 权限被拒绝
                    new ToastDialog(this)
                            .setDuration(2500)
                            .setText("拒绝授权部分功能将无法使用,请手动开启")
                            .show();
                }
                return;
            default:
                break;
        }
    }

}
